<template>
  <div>
    <MainHeader/>
    <!-- 下拉框 -->
    <!--    <div>-->
    <!--      <el-select v-model="selectedDepartmentId" placeholder="请选择"-->
    <!--                 @change="handleDepartmentChange()">-->
    <!--        <el-option-->
    <!--            v-for="item in departments"-->
    <!--            :key="item.id"-->
    <!--            :label="item.name"-->
    <!--            :value="item.id">-->
    <!--        </el-option>-->
    <!--      </el-select>-->
    <!--    </div>-->

    <!--  下拉框  -->
    <div>
      <!--一级分类-->
      <el-select
          v-model="courseInfo.id"
          placeholder="一级科室" @change="subjectLevelOneChanged">
        <el-option
            v-for="subject in departments"
            :key="subject.id"
            :label="subject.name"
            :value="subject.id"/>
      </el-select>

      <!-- 二级分类 -->
      <el-select v-model="courseInfo.pid" placeholder="二级科室" @change="handleDepartmentChange(courseInfo.pid)">
        <el-option
            v-for="subject in subjectTwoList"
            :key="subject.value"
            :label="subject.name"
            :value="subject.id"/>
      </el-select>
    </div>

    <div class=" calendar
        ">
      <!-- 星期-->
      <div class="header">
        <span v-for="(day, index) in displayedDays" :key="index">{{ day }}</span>
      </div>
      <div class="dates">
        <div v-for="(date, index) in displayedDates" :key="index" class="date-item"
             :class="{ active: isActiveDate(index) }" @click="handleDateClick(index)">
          <!-- 日期 -->
          <span :class="{ today: isToday(date) }">{{ formatDate(date) }}</span>
          <!-- 有号、无号 -->
          <div class="schedule-info" @click="handleDateClick(index)">
            <span v-if="schedule[index]" class="onDuty">有号</span>
            <span v-else class="noDuty">无号</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 医生信息 -->
    <div>
      <el-card v-if="doctorInfo.length > 0" class="box-card" v-for="(doctor, index) in doctorInfo" :key="index">
        <!-- 路由跳转 -->
        <router-link :to="{ name: 'schedulingABC', params: { id: doctor[0].id, date: formatDate(selectedDate) } }"
                     class="doctor-link">
          <!-- 出诊医生卡片-->
          <div class="content">
            <!--  头像区域 -->
            <div class="left-column">
              <div class="square-image">
                <img src="../image/ll.jpg"/>
              </div>
            </div>
            <!-- 右边区域显示医生信息-->
            <div class="right-column">
              <div class="info">
                <span><a class="name">医生姓名:</a>{{ doctor[0].name }}</span>
                <el-divider direction="vertical"/>
                <span><a class="name">医生职位:</a>{{ doctor[0].introduce }}</span>
              </div>
              <el-divider/>
              <div class="specialty">
                <span><b>擅长：</b>{{ doctor[0].proficientIn }}</span>
              </div>
            </div>
          </div>
          <!--  医生出诊时间  -->
          <div class="schedule">
            <span><b>出诊：</b>{{ doctor.schedule.scheduling === 0 ? '上午' : '下午' }}</span>
          </div>
        </router-link>
      </el-card>
      <!-- 不出诊医生提示 -->
      <div v-if="doctorInfo.length === 0" class="no-doctor">
        当天暂无医生值班
      </div>
    </div>
  </div>
</template>

<script>
import MainHeader from "@/views/MainHeader.vue";

export default {
  components: {MainHeader},
  data() {
    return {
      // 当前日期
      currentDate: new Date(),
      // 显示的日期数组
      displayedDates: [],
      // 显示的星期数组
      displayedDays: [],
      // 每日医生值班情况数组，true表示有医生值班，false表示无医生值班
      schedule: [],
      // 当前高亮日期的索引
      activeIndex: null,
      // 存放排班全部信息
      scheduling: [],
      // 保存医生信息+医生排班信息
      doctorInfo: [],
      // 列表的尺寸
      size: '',
      // 保存当前日期
      selectedDate: "",
      // 保存科室信息  一级
      departments: [],
      //  二级
      subjectTwoList: [],
      // 用于保存查询玩的医生id,
      dockerIds: [],
      courseInfo: {
        pid: '',      //二级分类id
        id: '', //一级分类id
      }
    };
  },
  methods: {
    // 生成日历方法
    generateCalendar() {
      const today = new Date(this.currentDate);
      const displayedDates = []; // 显示日期
      const displayedDays = [];  // 显示天
      // 循环生成7天的日期和对应的星期
      for (let i = 0; i < 7; i++) {
        const currentDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + i);
        displayedDates.push(currentDate);
        displayedDays.push(this.getWeekday(currentDate.getDay()));
      }
      // 更新显示的日期和星期数组
      this.displayedDates = displayedDates;
      this.displayedDays = displayedDays;
    },
    // 获取星期的名称
    getWeekday(dayIndex) {
      const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
      return weekdays[dayIndex];
    },
    // 判断日期是否为今天
    isToday(date) {
      const today = new Date().getDate();
      return date.getDate() === today;
    },
    // 处理日期点击事件
    handleDateClick(index) {
      // 如果当前正在执行查询，则不允许再次点击
      if (this.isQuerying) {
        return;
      }
      // 如果 dockerIds 数组为空，则不执行点击事件
      if (this.dockerIds.length === 0) {
        console.log("dockerIds 数组为空，无法执行请求数据的逻辑");

        return;
      }
      // 设置查询状态为 true
      this.isQuerying = true;
      // 清空医生信息数组
      this.doctorInfo = [];
      // 设置当前活动日期的索引
      this.activeIndex = index;
      // 获取日期对应的数据
      this.selectedDate = this.displayedDates[index];
      // 增加一天以获取正确的日期
      const correctDate = new Date(this.selectedDate);
      correctDate.setDate(correctDate.getDate() + 1);
      console.log("ids:///:", this.dockerIds)
      this.$axios.post(`/Scheduling/date/${correctDate.toISOString().substring(0, 10)}`, this.dockerIds
      ).then(res => {
        // 成功获取数据，处理医生数据并在前端页面显示
        this.scheduling = res.data;
        console.log('当天值班医生数据：', this.scheduling);

        // 检查是否有医生值班数据返回
        if (Array.isArray(this.scheduling) && this.scheduling.length > 0) {
          this.scheduling.forEach(doctor => {
            console.log("doctor:", doctor)
            // 将es做查询需要的参数包装到map里面
            let search = {'id': doctor.dockerId + ''};
            let map = {'search': JSON.stringify(search)};
            this.$axios.post("/search/docker", map)
                .then(res => {
                  // 成功获取医生信息
                  let doctorInfo = res.data.data;
                  console.log("res:", res)
                  console.log('医生信息：', doctorInfo);
                  // 将排班信息添加到医生信息对象中
                  doctorInfo.schedule = doctor;
                  // 将医生信息对象存储到数组中
                  this.doctorInfo.push(doctorInfo);
                  console.log("医生排班信息", doctor);
                  console.log('医生信息：', this.doctorInfo);
                })
          })
        }
      }).catch(error => {
        // 处理请求错误
        console.error('获取当天值班医生数据错误:', error);
      }).finally(() => {
        // 查询结束后，设置查询状态为 false，允许下次点击
        this.isQuerying = false;
      });
    },
    // 获取一周内上班的医生信息
    fetchDoctorSchedule() {
      this.$axios.get('/Scheduling/doctors/weekly')
          .then(res => {
            // 成功获取数据，更新医生排班信息
            const doctorSchedule = res.data;
            this.schedule = this.generateDoctorSchedule(doctorSchedule);
          }).catch(error => {
        // 处理请求错误
        console.error('获取每周医生错误:', error);
      });
    },
    // 根据医生排班信息生成每日医生值班情况数组
    generateDoctorSchedule(doctorSchedule) {
      // console.log("一周排班表信息：", doctorSchedule);
      const schedule = new Array(7).fill(false); // 初始化每日医生值班情况为false
      // 获取当前日期的星期索引
      const currentDayIndex = this.currentDate.getDay();
      // 循环医生排班信息，设置每日医生值班情况
      doctorSchedule.forEach(doctor => {
        // 获取医生值班日期的星期索引
        const dateIndex = new Date(doctor.date).getDay();
        // console.log("dateIndex", dateIndex)
        // 计算在 schedule 数组中的索引
        let scheduleIndex = dateIndex - currentDayIndex;
        if (scheduleIndex < 0) {
          // 如果索引为负数，表示值班日期在上一周，需要加 7 天
          scheduleIndex += 7;
        }
        // 将值班日期对应的 schedule 索引标记为有医生值班
        schedule[scheduleIndex] = true;
      });
      // console.log("schedule", schedule);
      return schedule;
    },
    // 判断日期是否为活动日期
    isActiveDate(index) {
      return this.activeIndex === index;
    },
    // 格式化日期为月份加上日期
    formatDate(date) {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}月${day}日`;
    },
    // 拿到科室
    doctorDepartment() {
      this.$axios.get("/search/all-departmentChild")
          .then(res => {
            // 成功获取医生信息
            this.departments = res.data;
            console.log(this.departments);
          })
    },
    //点击某个一级分类，会触发change事件，显示对应的二级分类
    subjectLevelOneChanged(value) {
      //value就是一级分类的id值，先遍历所有的分类 里面包含一级和二级
      for (var i = 0; i < this.departments.length; i++) {
        //每个一级分类
        var oneSubject = this.departments[i]
        //判断：所有一级分类id和点击一级分类id是否一样
        if (value === oneSubject.id) {  //===即比较值 还要比较类型
          //从一级分类中获取所有的二级分类
          this.subjectTwoList = oneSubject.childDepartment
          //把二级分类Id值清空
          this.courseInfo.pid = ''
        }
      }
    },
    // 通过科室id拿到属于这个科室的医生id
    handleDepartmentChange() {
      console.log("点击事件执行了，选中的二级科室id为：", this.courseInfo.pid);
      this.$axios.get(`/Scheduling/docker/id/${this.courseInfo.pid}`)
          .then(res => {
            this.dockerIds = res.data;
            console.log("医生：", this.dockerIds);
            // 清空医生信息数组
            this.doctorInfo = [];
            // 重新生成日历和查询医生排班信息
            this.generateCalendar();
            this.fetchDoctorSchedule();
            // 如果有选中的日期，则重新执行点击事件
            if (this.activeIndex !== null) {
              this.handleDateClick(this.activeIndex);
            }
          }).catch(error => {
        console.error("获取医生信息失败：", error);
      });
    }
  },
  mounted() {
    this.generateCalendar();
    this.fetchDoctorSchedule(); // 在组件加载时调用后台接口获取医生排班信息
    // 获取当前日期的索引
    const todayIndex = this.displayedDates.findIndex(date => this.isToday(date));
    if (todayIndex !== -1) {
      // 执行查询操作
      this.handleDateClick(todayIndex);
      // 拿到科室
      this.doctorDepartment();
      // 查询二级菜单
      this.subjectLevelOneChanged();
    }
  }
};
</script>

<style scoped>
/* 日期样式 */
.calendar {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.header {
  display: flex;
  width: 100%;
  justify-content: space-around;
  padding: 10px 0;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ccc;
}

.header span {
  flex: 1;
  text-align: center;
  font-weight: bold;
}

.dates {
  display: flex;
  width: 100%;
}

.date-item {
  flex: 1;
  text-align: center;
  padding: 20px 0;
  border-right: 1px solid #ccc;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.date-item:hover {
  background-color: #e0e0e0;
}

.date-item:last-child {
  border-right: none;
}

.schedule-info {
  margin-top: 10px;
}

.onDuty {
  color: green;
}

.noDuty {
  color: red;
}

.active {
  background-color: lightblue;
}

/* 贺卡 */
.box-card {
  display: flex;
  flex-direction: column; /* 修改为垂直布局 */
  align-items: flex-start; /* 左对齐 */
  padding: 3px;
  border-radius: 10px;
  transition: box-shadow 0.3s ease; /* 添加过渡效果 */
  width: 500px;
  margin: 15px; /* 添加外边距样式 */
}

.box-card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); /* 鼠标悬停时添加阴影效果 */
}


.content {
  display: flex;
  width: 100%;
}

.left-column {
  flex: 1;
  margin-right: 20px; /* 调整左右列之间的间距 */
}

.right-column {
  flex: 5;
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 左对齐 */
}

.square-image {
  width: 100px;
  height: 100px;
}

.square-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info span,
.specialty span,
.schedule span {
  display: block;
  margin-bottom: 10px;
}

.info {
  display: flex;
  align-items: center;
}

.info .name {
  margin-right: 10px;
  font-weight: bold;
  font-size: 18px;
}

.specialty span,
.schedule span:first-child {
  font-weight: bold; /* 加粗 */
}

.specialty span {
  color: #666;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  max-width: 18em;
}

.schedule span {
  color: #666;
}

.schedule {
  display: flex;
  align-items: flex-start; /* 左对齐 */
}

/* 去掉路由链接下划线 */
.doctor-link {
  text-decoration: none;
}
</style>
